package com.analysis.controller;

import com.analysis.dto.ApiResponse;
import com.analysis.entity.Project;
import com.analysis.entity.User;
import com.analysis.enums.RequireLogin;
import com.analysis.service.ProjectService;
import com.analysis.utils.UserUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目管理
 */
@RestController
@RequestMapping("/api/projects")
@CrossOrigin(origins = "*")
public class ProjectController {

    @Autowired
    private ProjectService projectService;

    @PostMapping("/add")
    @RequireLogin
    public ApiResponse<Project> create(@RequestBody Project project, HttpServletRequest request) {
        try {
            initProject(project, request);

            // 检查项目名称是否已存在（公司维度）
            if (projectService.existsByCompanyIdAndProjectName(project.getCompanyId(), project.getProjectName())) {
                return ApiResponse.error("项目名称已存在，请使用其他名称");
            }

            int result = projectService.create(project);
            return result > 0 ? ApiResponse.success(project) : ApiResponse.error("创建失败");
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("创建项目时发生错误: " + e.getMessage());
        }
    }

    @PostMapping("/delete")
    @RequireLogin
    public ApiResponse<String> delete(HttpServletRequest request, Long id) {
        try {
            User currentUser = UserUtils.getCurrentUserOrThrow(request, "用户未登录，无法删除项目");

            // 检查项目是否存在且属于当前公司
            Project existingProject = projectService.getById(id);
            if (existingProject == null || !existingProject.getCompanyId().equals(currentUser.getCompanyId())) {
                return ApiResponse.error("项目不存在或无权限操作");
            }

            int result = projectService.delete(id);
            return result > 0 ? ApiResponse.success("删除成功") : ApiResponse.error("删除失败或不存在");
        } catch (Exception e) {
            return ApiResponse.error("删除项目时发生错误: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    @RequireLogin
    public ApiResponse<Project> update(@RequestBody Project project, HttpServletRequest request) {
        try {
            initProject(project, request);

            // 检查项目是否存在且属于当前公司
            Project existingProject = projectService.getById(project.getId());
            if (existingProject == null || !existingProject.getCompanyId().equals(project.getCompanyId())) {
                return ApiResponse.error("项目不存在或无权限操作");
            }

            // 如果项目名称发生变化，检查新名称是否已存在
            if (!existingProject.getProjectName().equals(project.getProjectName()) &&
                    projectService.existsByCompanyIdAndProjectName(project.getCompanyId(), project.getProjectName())) {
                return ApiResponse.error("项目名称已存在，请使用其他名称");
            }

            int result = projectService.update(project);
            return result > 0 ? ApiResponse.success(projectService.getById(project.getId())) : ApiResponse.error("更新失败");
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("更新项目时发生错误: " + e.getMessage());
        }
    }

    @GetMapping("/get")
    @RequireLogin
    public ApiResponse<Project> getById(Long id, HttpServletRequest request) {
        try {
            User currentUser = UserUtils.getCurrentUserOrThrow(request, "用户未登录，无法查询项目");
            Project project = projectService.getById(id);

            if (project == null || !project.getCompanyId().equals(currentUser.getCompanyId())) {
                return ApiResponse.error("项目不存在或无权限访问");
            }

            return ApiResponse.success(project);
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("查询项目时发生错误: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    @RequireLogin
    public ApiResponse<List<Project>> list(HttpServletRequest request) {
        try {
            User currentUser = UserUtils.getCurrentUserOrThrow(request, "用户未登录，无法查询项目列表");
            List<Project> list = projectService.listByCompany(currentUser.getCompanyId());
            return ApiResponse.success(list);
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("查询项目列表时发生错误: " + e.getMessage());
        }
    }

    @GetMapping("/page")
    @RequireLogin
    public ApiResponse<Map<String, Object>> page(@RequestParam int pageNum, @RequestParam int pageSize, HttpServletRequest request) {
        try {
            User currentUser = UserUtils.getCurrentUserOrThrow(request, "用户未登录，无法查询项目");
            List<Project> list = projectService.page(currentUser.getCompanyId(), pageNum, pageSize);
            int total = projectService.count(currentUser.getCompanyId());
            Map<String, Object> data = new HashMap<>();
            data.put("list", list);
            data.put("total", total);
            data.put("pageNum", pageNum);
            data.put("pageSize", pageSize);
            return ApiResponse.success(data);
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("分页查询项目时发生错误: " + e.getMessage());
        }
    }

    /**
     * 用户当前选中的项目
     *
     * @param request
     * @return
     */
    @GetMapping("/selected")
    @RequireLogin
    public ApiResponse<Project> getSelected(HttpServletRequest request) {
        try {
            User currentUser = UserUtils.getCurrentUser(request);
            Project selectedProject = projectService.getSelectedByCompanyId(currentUser.getCompanyId());
            return ApiResponse.success(selectedProject);
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("查询当前选中项目时发生错误: " + e.getMessage());
        }
    }

    @PostMapping("/select")
    @RequireLogin
    public ApiResponse<String> selectProject(@RequestParam Long projectId, HttpServletRequest request) {
        try {
            User currentUser = UserUtils.getCurrentUser(request);

            // 验证项目是否属于当前公司
            Project project = projectService.getById(projectId);
            if (project == null || !project.getCompanyId().equals(currentUser.getCompanyId())) {
                return ApiResponse.error("项目不存在或无权限操作");
            }

            int result = projectService.selectProject(currentUser.getCompanyId(), projectId);
            return result > 0 ? ApiResponse.success("项目选择成功") : ApiResponse.error("项目选择失败");
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("选择项目时发生错误: " + e.getMessage());
        }
    }

    @PostMapping("/unselect")
    @RequireLogin
    public ApiResponse<String> unselectAll(HttpServletRequest request) {
        try {
            User currentUser = UserUtils.getCurrentUserOrThrow(request, "用户未登录，无法取消选择");
            int result = projectService.unselectAllByCompanyId(currentUser.getCompanyId());
            return result >= 0 ? ApiResponse.success("取消选择成功") : ApiResponse.error("取消选择失败");
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("取消选择时发生错误: " + e.getMessage());
        }
    }


    private void initProject(Project project, HttpServletRequest request) {
        User currentUser = UserUtils.getCurrentUser(request);
        project.setUserId(currentUser.getId());
        project.setCompanyId(currentUser.getCompanyId());
    }
}
